﻿jQuery.FlyComet = function (callme, objectname) {
    var connected = false;
    var HashMappie = new Map();
    var onMessageReceived = callme;
    var requestid = null;
    var subscribedonce = false;
    var counter = 0;
    var lastrequestsent = null;
    var verupdatefreq = 0;

    var Connect = function () {
        $.ajax(
            {
                type: 'get',
                url: '/FlyCometHandler.ashx?command=connect',
                async: true,
                success: function (data) {
                    var conobj = eval('(' + data + ')');
                    if (conobj == null) {
                        alert("Error Connecting to Live Updater");
                        return;
                    }
                    if (conobj.StatusCode == 0) {
                        connected = true;
                        requestid = conobj.RequestId;
                    }
                    onMessageReceived("connect", conobj.StatusDescription);
                },
                error: function (ex) {
                    onMessageReceived("connect", "Error:" + ex.toString());
                }
            }
            );
    }

    var Disconnect = function () {
        connected = false;
        $.ajax(
            {
                type: 'get',
                url: '/FlyCometHandler.ashx?command=disconnect&requestkey=' + requestid,
                async: true,
                success: function (data) {
                    onMessageReceived("disconnect", data);
                },
                error: function (ex) {
                    onMessageReceived("disconnect", "Error:" + ex.toString());
                }
            }
            );

    }

    var SubscribeToChannel = function (TopicId, showalert) {
        if (connected == false) {
            throw new Error("Connection to Live Update Server is not established yet.");
        }
        if (TopicId == null) {
            throw new Error("_Subscription requires an object with 'topicId' property set to a positive integer.");
        }
        var DeviceFound = HashMappie.get(TopicId);

        if (DeviceFound == null) {
            $.ajax(
            {
                type: 'get',
                url: '/FlyCometHandler.ashx?command=subscribe&requestkey=' + requestid + "&channel=" + TopicId,
                async: true,
                success: function (data) {
                    if (subscribedonce != true) {
                        timeoutHnd = setTimeout(function () { RequestUpdates(); }, 1000);
                        VerifyUpdateFrequency();
                    }
                    onMessageReceived("subscribe", data);
                    if (showalert == true)
                        alert(data);
                    subscribedonce = true;
                },
                error: function (ex) {
                    onMessageReceived("subscribe", "Error:" + ex.toString());
                }

            }
            );

            HashMappie.put(TopicId, "true");
            if (showalert == true)
                alert('Subscribed Successfully');
        }
        else {
            if (showalert == true)
                alert('Already Subscribed');
        }
    }

    var RemoveSubscription = function (TopicId) {
        var DeviceFound = HashMappie.get(TopicId);

        if (DeviceFound != null) {
            $.ajax(
            {
                type: 'get',
                url: '/FlyCometHandler.ashx?command=unsubscribe&requestkey=' + requestid + "&channel=" + TopicId,
                async: true,
                success: function (data) {
                    onMessageReceived("unsubscribe", data);
                },
                error: function (ex) {
                    onMessageReceived("unsubscribe", "Error:" + ex.toString());
                }

            }
            );
            HashMappie.remove(TopicId);
        }
    }
    var VerifyUpdateFrequency = function () {
        var now = new Date();

        if (lastrequestsent != null && lastrequestsent.setTime(now.getTime() + 15000) < now) {
            if (timeoutHnd) { clearTimeout(timeoutHnd); }
            timeoutHnd = setTimeout(function () { RequestUpdates(); }, 3000);
        }
        if (verupdatefreq) { clearTimeout(verupdatefreq); }
        verupdatefreq = setTimeout(function () { VerifyUpdateFrequency(); }, 10000);
    }
    var RequestUpdates = function () {
        lastrequestsent = new Date();
        var devicecount = HashMappie.size();
        if (subscribedonce == true) {
            $.ajax(
            {
                type: 'get',
                url: '/FlyCometHandler.ashx?command=receive&requestkey=' + requestid,
                async: true,
                success: function (data) {
                    var msgobject = eval('(' + data + ')');
                    if (msgobject == null || msgobject.StatusCode == 0) {
                        onMessageReceived("data", msgobject.Message);
                    }
                    if (devicecount >= 1) {
                        if (timeoutHnd) { clearTimeout(timeoutHnd); }
                        timeoutHnd = setTimeout(function () { RequestUpdates(); }, 3000);
                    }
                },
                error: function (ex) {
                    if (devicecount >= 1) {
                        if (timeoutHnd) { clearTimeout(timeoutHnd); }
                        timeoutHnd = setTimeout(function () { RequestUpdates(); }, 3000);
                    }
                }
            }
        );
        }
    }
    return {
        Connect: Connect,
        SubscribeToChannel: SubscribeToChannel,
        RemoveSubscription: RemoveSubscription,
        Disconnect: Disconnect,
        RequestUpdates: RequestUpdates
    }
}
